package com.example.safeassistan.risk.fragment;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.safeassistan.R;
import com.example.safeassistan.base.BaseVPFragment;
import com.example.safeassistan.constants.UrlConstants;
import com.example.safeassistan.hiddendanger.model.DepartModel;
import com.example.safeassistan.home.activity.ActivityCheckLog;
import com.example.safeassistan.home.activity.HiddenDangerinvestigation;
import com.example.safeassistan.home.activity.RiskPointDetail;
import com.example.safeassistan.home.activity.RiskPointList;
import com.example.safeassistan.home.activity.WarnningList;
import com.example.safeassistan.home.model.MyBackLogListModel;
import com.example.safeassistan.http.HttpRequest;
import com.example.safeassistan.http.HttpStringCallBack;
import com.example.safeassistan.risk.adapter.DepartSelectedListAdapter;
import com.example.safeassistan.risk.adapter.RiskDepartmentListAdapter;
import com.example.safeassistan.risk.adapter.RiskMyListAdapter;
import com.example.safeassistan.risk.model.DepartListModel;
import com.example.safeassistan.risk.model.RiskPointLevelStatModel;
import com.example.safeassistan.risk.model.RiskPointListSearchModel;
import com.example.safeassistan.risk.model.WarnningModel;
import com.example.safeassistan.train.activity.ActivityTrainResult;
import com.example.safeassistan.train.model.PaperResultModel;
import com.example.safeassistan.utile.JsonUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.example.safeassistan.constants.Constants.PAGESIZE;

public class RiskDepartmentFragment extends BaseVPFragment implements View.OnClickListener {
    private Context context;
    private View view;
    private TextView tvDegree,tvStatus,tvDepartName,tvTip;
    private LinearLayout llStatus,llDegree,llWarnning;
    private RiskDepartmentListAdapter adapter;
    private List<RiskPointListSearchModel.ResultDTO.RecordsDTO> data;
    private RecyclerView rcView;
    private SmartRefreshLayout refresh;
    private int type=0;
    private TextView tvMore;
    private LinearLayout llSearch,llDepartment;
    private PopupWindow popupWindow=null;
    private TextView tvBigRisk,tvBiggerRisk,tvRiskCommon,tvRiskLow,tvRiskTotal;
    private DepartModel departListModel=null;
    private int riskLevel=-1;
    private int isOutOfControl=-1;
    private String departId="";//部门id
    private int screenWidth=0;
    private int currentPage=1;
    private int count=0;

    public static RiskDepartmentFragment newInstance(int  type) {
        Bundle arguments = new Bundle();
        arguments.putInt("type",type);
        RiskDepartmentFragment fl = new RiskDepartmentFragment();
        fl.setArguments(arguments);
        return fl;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.risk_department_fragment, container, false);
            context = getActivity();
            initView();
        }
        return view;
    }

    public void initView(){
        DisplayMetrics dm = new DisplayMetrics();
        dm = getResources().getDisplayMetrics();
        screenWidth = dm.widthPixels; // 屏幕宽（像素，如：3200px）

        Bundle bundle = getArguments();
         type = bundle.getInt("type",0);
        rcView=view.findViewById(R.id.rcView);
        refresh=view.findViewById(R.id.refresh);
        tvTip=view.findViewById(R.id.tvTip);
        llWarnning=view.findViewById(R.id.llWarnning);
        tvMore=view.findViewById(R.id.tvMore);
        tvRiskLow=view.findViewById(R.id.tvRiskLow);
        llDegree=view.findViewById(R.id.llDegree);
        tvRiskTotal=view.findViewById(R.id.tvRiskTotal);
        llStatus=view.findViewById(R.id.llStatus);
        tvDepartName=view.findViewById(R.id.tvDepartName);
        tvRiskCommon=view.findViewById(R.id.tvRiskCommon);
        tvBiggerRisk=view.findViewById(R.id.tvBiggerRisk);
        tvBigRisk=view.findViewById(R.id.tvBigRisk);
        tvDegree=view.findViewById(R.id.tvDegree);
        tvStatus=view.findViewById(R.id.tvStatus);
        llSearch=view.findViewById(R.id.llSearch);
        llDepartment=view.findViewById(R.id.llDepartment);
        llDepartment.setOnClickListener(this);
        llSearch.setOnClickListener(this);
        tvMore.setOnClickListener(this);
        llStatus.setOnClickListener(this);
        llDegree.setOnClickListener(this);


    }

    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {
        if (isVisible){
            getWarnning();
        }
    }

    @Override
    protected void onFragmentFirstVisible() {
        setView();
        getMidData();
        getData();
        getDepartListData();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.llStatus:
                View inflate = LayoutInflater.from(context).inflate(R.layout.popu_risk_status,null);
                TextView tvStatu=inflate.findViewById(R.id.tvStatus);
                tvStatu.setWidth(llStatus.getWidth());
                tvStatu.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        isOutOfControl=-1;
                        popupWindow.dismiss();
                        tvStatus.setText("状态");
                        tvStatus.setTextColor(context.getColor(R.color.gray3));
                        getData();
                        getMidData();
                    }
                });

                TextView tvControl=inflate.findViewById(R.id.tvControl);
                tvControl.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        isOutOfControl=0;
                        popupWindow.dismiss();
                        tvStatus.setText("受控");
                        tvStatus.setTextColor(context.getColor(R.color.blue_3B5BEA));
                        getData();
                        getMidData();
                    }
                });

                TextView tvEarlyWarrning=inflate.findViewById(R.id.tvEarlyWarrning);
                tvEarlyWarrning.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        isOutOfControl=1;
                        popupWindow.dismiss();
                            tvStatus.setText("预警");
                        tvStatus.setTextColor(context.getColor(R.color.blue_3B5BEA));
                        getData();
                        getMidData();
                    }
                });
                popupWindow = new PopupWindow(inflate, RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
                //设置背景,这个没什么效果，不添加会报错
                popupWindow.setBackgroundDrawable(new BitmapDrawable());
                //设置点击弹窗外隐藏自身
                popupWindow.setFocusable(true);
                popupWindow.setOutsideTouchable(true);
                //相对于某一个控件的位置
                popupWindow.showAsDropDown(llStatus,0,-100);
                break;
            case R.id.llDegree:
                View inflate1 = LayoutInflater.from(context).inflate(R.layout.popu_risk_level,null);
                TextView tvAll=inflate1.findViewById(R.id.tvAll);
                tvAll.setWidth(llDegree.getWidth());
                tvAll.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        riskLevel=-1;
                        popupWindow.dismiss();
                        tvDegree.setText("风险等级");
                        tvDegree.setTextColor(context.getResources().getColor(R.color.gray3));
                        getData();
                        getMidData();
                    }
                });
                TextView tvBig=inflate1.findViewById(R.id.tvBig);
                tvBig.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        riskLevel=1;
                        popupWindow.dismiss();
                        tvDegree.setText("重大风险");
                        tvDegree.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        getData();
                        getMidData();
                    }
                });
                TextView tvBigger=inflate1.findViewById(R.id.tvBigger);
                tvBigger.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        riskLevel=2;
                        popupWindow.dismiss();
                        tvDegree.setText("较大风险");
                        tvDegree.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        getData();
                        getMidData();
                    }
                });
                TextView tvCommon=inflate1.findViewById(R.id.tvCommon);
                tvCommon.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        riskLevel=3;
                        popupWindow.dismiss();
                        tvDegree.setText("一般风险");
                        tvDegree.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        getData();
                        getMidData();
                    }
                });
                TextView tvLow=inflate1.findViewById(R.id.tvLow);
                tvLow.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        riskLevel=4;
                        popupWindow.dismiss();
                        tvDegree.setText("较低风险");
                        tvDegree.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        getData();
                        getMidData();
                    }
                });
                popupWindow = new PopupWindow(inflate1, RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
                //设置背景,这个没什么效果，不添加会报错
                popupWindow.setBackgroundDrawable(new BitmapDrawable());
                //设置点击弹窗外隐藏自身
                popupWindow.setFocusable(true);
                popupWindow.setOutsideTouchable(true);
                //相对于某一个控件的位置
                popupWindow.showAsDropDown(llDegree,0,-100);
                break;
            case R.id.llDepartment:
                //请求部门列表数据
                View inflate2 = LayoutInflater.from(context).inflate(R.layout.layout_popuwindow_department,null);
                TextView tvAlls=inflate2.findViewById(R.id.tvAll);
                tvAlls.setWidth(llDepartment.getWidth());
                tvAlls.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        departId="";
                        popupWindow.dismiss();
                        tvDepartName.setText("部门选择");
                        tvDepartName.setTextColor(context.getResources().getColor(R.color.gray3));
                        getData();
                    }
                });
                RecyclerView rcView=inflate2.findViewById(R.id.rcView);
                DepartSelectedListAdapter adapter=new DepartSelectedListAdapter(departListModel.getResult());
                rcView.setAdapter(adapter);
                rcView.setLayoutManager(new LinearLayoutManager(context));
                adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        departId=departListModel.getResult().get(position).getId();
                        popupWindow.dismiss();
                        tvDepartName.setText(departListModel.getResult().get(position).getName());
                        tvDepartName.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        getData();
                    }
                });
                popupWindow = new PopupWindow(inflate2, RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
                //设置背景,这个没什么效果，不添加会报错
                popupWindow.setBackgroundDrawable(new BitmapDrawable());
                //设置点击弹窗外隐藏自身
                popupWindow.setFocusable(true);
                popupWindow.setOutsideTouchable(true);
                //相对于某一个控件的位置
                popupWindow.showAsDropDown(llDepartment,0,-100);
                break;
            case R.id.tvMore:
                WarnningList.actionStart(context,"1","");
                break;
            case R.id.llSearch:
                // 搜索
                RiskPointList.actionStart(context,2);
                break;
        }
    }
    public void getDepartListData(){
        new HttpRequest(context).doPost(UrlConstants.getDepartById, null, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), DepartModel.class);
                        if (obj instanceof DepartModel) {
                            departListModel=(DepartModel) obj;
                        }else {
                            Log.e("aaaa","哈哈哈哈哈");
                        }
                    }else {
                        Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }

    public void getMidData(){
        JSONObject object=new JSONObject();
        try {
            if(riskLevel!=-1){
                object.put("riskLevel",riskLevel);//风险等级
            }
            object.put("selectType",String.valueOf(2));//搜索类型 1 我的 2 部门
            if (isOutOfControl!=-1){
                object.put("isOutOfControl",String.valueOf(isOutOfControl));//是否受控
            }
            if (departId!=null&&!departId.equals("")){
                object.put("departId",departId);//是否受控
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new HttpRequest(context).doPost(UrlConstants.getPointLevelStat, null, object,new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    int  code = jsonObject.getInt("code");
                    if (code==200) {
                        Object obj = JsonUtils.fromJson(result.toString(), RiskPointLevelStatModel.class);
                        if (obj instanceof RiskPointLevelStatModel) {
                            RiskPointLevelStatModel  riskPointLevelStatModel=(RiskPointLevelStatModel) obj;
                            tvBigRisk.setText(riskPointLevelStatModel.getResult().getRiskLevel1()+"");
                            tvBiggerRisk.setText(riskPointLevelStatModel.getResult().getRiskLevel2()+"");
                            tvRiskCommon.setText(riskPointLevelStatModel.getResult().getRiskLevel3()+"");
                            tvRiskLow.setText(riskPointLevelStatModel.getResult().getRiskLevel4()+"");
                            tvRiskTotal.setText(riskPointLevelStatModel.getResult().getTotal()+"");
                        }else {
                            Log.e("aaaa","哈哈哈哈哈");
                        }
                    }else {
                        Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }

    public void setView(){
        data=new ArrayList<>();
        refresh.setEnableAutoLoadMore(true);//开启自动加载功能（非必须）
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentPage = 1;
                        getData();
                    }
                }, 1000);
            }
        });
        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentPage++;
                        getData();
                    }
                }, 1000);
            }
        });
    }

    // 获取数据
    public void getData(){
        JSONObject map = new JSONObject();
        try {
            if (!departId.equals("")){
                map.put("departId",departId);
            }
            map.put("pageNo", String.valueOf(currentPage));
            map.put("pageSize",String.valueOf(PAGESIZE));
            map.put("selectType",String.valueOf(2));//选择类型 1 我的 2 部门
            if (isOutOfControl!=-1){
                map.put("isOutOfControl",isOutOfControl);//是否受控
            }
            if (riskLevel!=-1){
                map.put("riskLevel",riskLevel);//风险等级
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new HttpRequest(context).doPost(UrlConstants.getRiskList, null, map, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), RiskPointListSearchModel.class);
                        if (obj instanceof RiskPointListSearchModel) {
                            RiskPointListSearchModel model=(RiskPointListSearchModel) obj;
                            if (currentPage == 1) {
                                data.clear();
                                count = model.getResult().getTotal();
                                if (model.getResult().getRecords().size() > 0) {
                                    data=model.getResult().getRecords();
                                    adapter=new RiskDepartmentListAdapter(data);
                                    rcView.setLayoutManager(new LinearLayoutManager(context));
                                    rcView.setAdapter(adapter);
                                    if (adapter.getItemCount() < count) {
                                        //还有多的数据
                                        refresh.finishRefresh();
                                    } else {
                                        //没有更多数据（上拉加载功能将显示没有更多数据）
                                        refresh.finishRefreshWithNoMoreData();
                                    }
                                    adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                            RiskPointDetail.actionStart(getContext(),data.get(position).getId(),riskLevel,"1");
                                        }
                                    });
                                } else {
                                    refresh.finishRefreshWithNoMoreData();
                                    adapter.notifyDataSetChanged();
                                }
                            } else {
                                data.addAll(model.getResult().getRecords());
                                adapter.notifyDataSetChanged();
                                if (adapter.getItemCount() < count) {
                                    //还有多的数据
                                    refresh.finishLoadMore();
                                } else {
                                    //没有更多数据（上拉加载功能将显示没有更多数据）
                                    refresh.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                                }
                            }
                        }
                    }else {
                        Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                refresh.finishLoadMore();
                refresh.finishRefresh();
            }
        });
    }


    public void getWarnning(){
        Map map=new HashMap<>();
        map.put("checkStatus","1");

        new HttpRequest(context).doGet(UrlConstants.risk_queryWarnRiskPointCount, null,map ,new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean  success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), WarnningModel.class);
                        if (obj instanceof WarnningModel) {
                            WarnningModel model=(WarnningModel)obj;
                            if (model.getResult()==0){
                                llWarnning.setVisibility(View.GONE);
                            }else {
                                llWarnning.setVisibility(View.VISIBLE);
                                tvTip.setText("有"+model.getResult()+"个风险点在预警状态");
                            }
                        }
                    }else {
                        Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }
}